/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/dao/Updater.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: Updater.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (周一, 02 七月 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.dao;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.elancom.framework.commons.util.StringUtils;
import com.elancom.framework.dao.internal.UpdateCompiledImpl;

/**
 * @author elancom
 * @date May 4, 2012
 */
public class Update extends AbstractStructureSupport<Update> {
	private transient Logger logger = LoggerFactory.getLogger(Update.class);

	private transient String updateString = new String();

	private transient StringBuilder setString = new StringBuilder();

	private transient boolean seted = false;

	private String updateStringCompile = null;

	private boolean compile = false;

	private Update set(String oneSetting) {
		if (StringUtils.isNotBlank(oneSetting)) {
			if (!seted) {
				setString.append(" set ");
				seted = true;
			} else {
				setString.append(", ");
			}
			setString.append(oneSetting);
		}
		return this;
	}

	public Update set(String name, Object value) {
		if (StringUtils.isNotBlank(name)) {
			set(name + " = :$$" + name).setParameter("$$" + name, value);
		}
		return this;
	}

	public Update update(String updateTarget) {
		updateString = updateTarget;
		return this;
	}

	public Update update(Class<?> clazz) {
		if (clazz != null) {
			update(clazz.getName());
		}
		return this;
	}

	public Update update(Class<?> clazz, String alias) {
		if (clazz != null) {
			update(clazz.getName() + " " + alias);
		}
		return this;
	}

	public String buildUpdateString() {
		final StringBuilder sb = new StringBuilder();
		sb.append("update ").append(updateString);
		sb.append(setString).append(whereString);

		final String queryString = sb.toString();

		if (logger.isDebugEnabled()) {
			logger.debug(queryString);
		}

		return queryString;
	}

	public UpdateCompiled compile() {
		this.updateStringCompile = buildUpdateString();
		this.compile = true;

		UpdateCompiledImpl compiled = new UpdateCompiledImpl();
		compiled.setUpdateString(this.updateStringCompile);
		compiled.setParameterMap(getParameterMap());

		return compiled;
	}

	/*
	 * (non-Javadoc)
	 * @see com.elancom.framework.dao.UpdateSupport#getUpdateString()
	 */
	public String getUpdateString() {
		if (!compile) {
			throw new RuntimeException("语句未被编译");
		}
		return this.updateStringCompile;
	}

	@Override
	public String toString() {
		return this.updateStringCompile;
	}

	public Map<String, Object> getParameterMap() {
		return this.paramMap;
	}
}
